// 一些单独接口
import { getFileContext, responseStatus, setFileContext } from './util'
import { managerFile, roleFile } from './filePath'
import path from 'path'
import dayjs from 'dayjs'
import fs from 'fs'
const multiparty = require('multiparty')

// 创建文件夹
function checkDir() {
  [
    path.join(__dirname, './upload/temp'),
    path.join(__dirname, './upload/cover'),
    path.join(__dirname, './upload/video')
  ].forEach(dir => {
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  })
}
export default [
  {
    url: '/api/login',
    method: 'post',
    timeout: 1000,
    response: ({ body }) => {
      const data = getFileContext(managerFile)
      const user = data.find(item => item.account === body.account && item.password === body.password)
      if (user) {
        // 获取角色权限
        const roles = getFileContext(roleFile)
        const roleInfo = roles.find(item => item.id === user.roleId)
        user.permissions = roleInfo ? roleInfo.permissions : []
        user.role = roleInfo ? roleInfo.name : null
        user.lastLoginTime = dayjs().format('YYYY-MM-DD hh:mm:ss')
        setFileContext(managerFile, data)
        return {
          ...responseStatus(),
          userInfo: user
        }
      }
      return {
        ...responseStatus(2),
        msg: '用户名或密码错误'
      }
    }
  },
  // 文件上传
  {
    url: '/api/upload',
    method: 'post',
    rawResponse: async (req, res) => {
      const uploadDir = path.join(__dirname, './upload/temp/')
      const form = new multiparty.Form({ uploadDir })
      form.parse(req, function (error, fields, files) {
        if (error) {
          res.end(JSON.stringify({ error }))
        } else {
          const { fileName, fileType, noSlice } = fields // noSlice存在则表示为一次性上传，否则为分片上传
          let newPath
          if (noSlice) {
            newPath = path.join(__dirname, './upload/cover/') + fileName.join() + '.' + fileType.join().replace('.', '')
          } else {
            newPath = uploadDir + fileName.join()
          }
          fs.renameSync(files.file[0].path, newPath) // 重命名文件名称
          res.end(JSON.stringify({
            code: 1,
            msg: '已上传',
            data: {
              ...fields,
              url: newPath.replace(/.+mock/, '/mock') // 返回前端相对路径
            }
          }))
        }
      })
    }
  },
  // 合并文件
  {
    url: '/api/merge',
    method: 'post',
    response: ({ body }) => {
      checkDir()
      const dirPath = path.join(__dirname, './upload/temp/')
      const filePath = path.join(__dirname, './upload/video/' + body.fileName + '.' + body.fileType)
      const writeStream = fs.createWriteStream(filePath)
      const files = fs.readdirSync(dirPath).sort()
      mergeFile(files, writeStream, (res) => {
        fs.readdirSync(dirPath).forEach(item => {
          console.log(item, body.fileName.split('.')[0])
          if (item.includes(body.fileName.split('.')[0])) {
            fs.unlinkSync(dirPath + item)
          }
        })
      })
      return {
        code: 1,
        url: filePath.replace(/.+mock/, '/mock'),
        msg: '上传成功'
      }
    }
  },
  // 查询文件是否已存在
  {
    url: '/api/checkUploadFile',
    method: 'post',
    response: ({ body }) => {
      let dirPath = path.join(__dirname, './upload/video/')
      let files = fs.readdirSync(dirPath).find(filePath => filePath.includes(body.fileName))
      if (files) {
        return {
          code: 1,
          url: `/mock/upload/video/${files}`,
          status: 1, // 已上传，服务器存在该文件
          msg: '请求成功'
        }
      }
      dirPath = path.join(__dirname, './upload/temp')
      files = fs.readdirSync(dirPath).filter(filePath => filePath.includes(body.fileName))
      if (files) {
        return {
          code: 1,
          files,
          status: 2, // 上传中，存在部分切片
          msg: '请求成功'
        }
      } else {
        return {
          code: 1,
          status: 3, // 未上传，服务器不存在相关文件
          msg: '请求成功'
        }
      }
    }
  }
]

function mergeFile (files = [], writeStream, cb) {
  if (files.length) {
    const readStream = fs.createReadStream(`${path.join(__dirname, './upload/temp')}/${files.shift()}`)
    readStream.pipe(writeStream, { end: false })
    readStream.on('end', () => {
      mergeFile(files, writeStream, cb)
    })
  } else {
    console.log(11234)
    cb()
    writeStream.end()
  }
}
